package com.fancylargo.crowd.service.impl;

import com.fancylargo.crowd.common.utils.PageUtils;
import com.fancylargo.crowd.common.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fancylargo.crowd.dao.CategoryDao;
import com.fancylargo.crowd.entity.CategoryEntity;
import com.fancylargo.crowd.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

//    @Autowired
//    CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商品分类，组装成属性结构
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        // 1、查询出所有的分类
        List<CategoryEntity> listCategory = baseMapper.selectList(null);
        // 2、组装成属性解构
        // 2.1 找到一级分类
        List<CategoryEntity> level = listCategory.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{
            menu.setChildren(getChildrens(menu,listCategory));
            return menu;
        }).sorted((menu1,menu2) -> {
            // 为菜单排序
            return (menu1.getSort() == null ? 0: (menu1.getSort())) - (menu2.getSort() == null ? 0 : menu2.getSort());
        } ).collect(Collectors.toList());

        return level;
    }

    /**
     * 获取每个菜单的子菜单
     * @param root
     * @param categoryEntityList
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> categoryEntityList){

        List<CategoryEntity> categoryChildren = categoryEntityList.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity,categoryEntityList));
            return categoryEntity;
        }).sorted((menu1,menu2) -> {
            // 排序
            return (menu1.getSort() == null ? 0: (menu1.getSort())) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return categoryChildren;
    }

    /**
     * 批量删除
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }






}